package com.anyview.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.anyview.mapper.CompanyGoodsMapper;
import com.anyview.po.CompanyGoods;
import com.anyview.service.ExcelTestService;
import com.anyview.vo.DownloadExcelVo;
import com.anyview.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import okhttp3.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class ExcelTestServiceImpl extends ServiceImpl<CompanyGoodsMapper, CompanyGoods> implements ExcelTestService {

    private static final String BOT_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/2298cfdb-adc3-48c7-b947-0a7ecd9feaa7";


    @Resource
    private ExcelReader excelReader;

    @Resource
    private CompanyGoodsMapper companyGoodsMapper;

    /**
     * 出货记录
     *
     * @param downloadExcelVo 1
     */
    @Override
    public ResponseEntity<byte[]> downloadExcelBetweenDate(DownloadExcelVo downloadExcelVo) {
        //1.获取时间
        Date start = new Date(downloadExcelVo.getStart_date());
        Date end = new Date(downloadExcelVo.getEnd_date());

        //2.查询数据库
        LambdaQueryWrapper<CompanyGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(CompanyGoods::getShippingTime, start, end);
        List<CompanyGoods> companyGoods = companyGoodsMapper.selectList(queryWrapper);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream, CompanyGoods.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.write(companyGoods, writeSheet);
        excelWriter.finish();

        byte[] bytes = outputStream.toByteArray();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("order", "data." + downloadExcelVo.getType());


        uploadFileToFeiShu(companyGoods);

        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);


    }

    /**
     * 将数据保存进数据库中
     *
     * @param file 文件
     * @return 返回响应结果
     */
    @Override
    @Transactional
    public Result<Boolean> excelImportDatabase(MultipartFile file) throws IOException {
        Boolean isSuccess = true;
        excelReader.readExcel(file, dataList -> {
            int batchSize = 1000;
            List<List<CompanyGoods>> partition = Lists.partition(dataList, batchSize);
            partition.parallelStream().forEach(subList -> {
                saveBatch(subList, batchSize);
            });
        });
        return Result.success(isSuccess);
    }

    /**
     * 将部分信息发送到飞书机器人中
     *
     * @param companyGoods 订单信息
     */
    private static void uploadFileToFeiShu(List<CompanyGoods> companyGoods) {
        //1.获取全部商品的和
        int maxNumber = 0;
        String companyName = null;
        int length = 0;
        int total = 0;
        for (CompanyGoods companyGood : companyGoods) {
            length++;
            total += companyGood.getGoodsNumber();
            if (companyGood.getGoodsNumber() > maxNumber) {
                maxNumber = companyGood.getGoodsNumber();
                companyName = companyGood.getCompanyName();
            }
        }

        OkHttpClient httpClient = new OkHttpClient();
        MediaType parse = MediaType.parse("application/json; charset=uft-8");

        String json = "{\n" +
                "    \"msg_type\": \"interactive\",\n" +
                "    \"card\": {\n" +
                "  \"i18n_elements\": {\n" +
                "    \"zh_cn\": [\n" +
                "      {\n" +
                "        \"tag\": \"div\",\n" +
                "        \"text\": {\n" +
                "          \"content\": \"发送者：曾中港\",\n" +
                "          \"tag\": \"plain_text\"\n" +
                "        }\n" +
                "      },\n" +
                "      {\n" +
                "        \"tag\": \"hr\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"tag\": \"column_set\",\n" +
                "        \"flex_mode\": \"bisect\",\n" +
                "        \"background_style\": \"grey\",\n" +
                "        \"horizontal_spacing\": \"default\",\n" +
                "        \"columns\": [\n" +
                "          {\n" +
                "            \"tag\": \"column\",\n" +
                "            \"width\": \"weighted\",\n" +
                "            \"weight\": 1,\n" +
                "            \"elements\": [\n" +
                "              {\n" +
                "                \"tag\": \"markdown\",\n" +
                "                \"text_align\": \"center\",\n" +
                "                \"content\": \"共计导出行数\\n**" + length + "**\"\n" +
                "              }\n" +
                "            ]\n" +
                "          },\n" +
                "          {\n" +
                "            \"tag\": \"column\",\n" +
                "            \"width\": \"weighted\",\n" +
                "            \"weight\": 1,\n" +
                "            \"elements\": [\n" +
                "              {\n" +
                "                \"tag\": \"markdown\",\n" +
                "                \"text_align\": \"center\",\n" +
                "                \"content\": \"货物数量总和\\n**" + total + "**\"\n" +
                "              }\n" +
                "            ]\n" +
                "          },\n" +
                "          {\n" +
                "            \"tag\": \"column\",\n" +
                "            \"width\": \"weighted\",\n" +
                "            \"weight\": 1,\n" +
                "            \"elements\": [\n" +
                "              {\n" +
                "                \"tag\": \"markdown\",\n" +
                "                \"text_align\": \"center\",\n" +
                "                \"content\": \"出货量最多的公司\\n**" + companyName + "**\"\n" +
                "              }\n" +
                "            ]\n" +
                "          }\n" +
                "        ]\n" +
                "      }\n" +
                "    ]\n" +
                "  },\n" +
                "  \"header\": {\n" +
                "    \"template\": \"blue\",\n" +
                "    \"title\": {\n" +
                "      \"tag\": \"plain_text\",\n" +
                "      \"i18n\": {\n" +
                "        \"zh_cn\": \"excel数据统计结果\"\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}\n" +
                "}";

        RequestBody requestBody = RequestBody.create(parse, json);

        Request request = new Request.Builder()
                .url(BOT_WEBHOOK)
                .post(requestBody)
                .build();
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println("发送成功");
            } else {
                System.out.println("发送失败：" + response.body().string());
            }
            System.out.println(response.body().string());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
